package com.framework.network.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author duanzhizhou
 * @date 2025/6/5
 */
public class Server {
    
    public static void main(String[] args) throws IOException {
        try (ServerSocketChannel ssc = ServerSocketChannel.open(); Selector selector = Selector.open()) {
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress("localhost", 8088));
            ssc.register(selector, SelectionKey.OP_ACCEPT);
            while (true) {
                selector.select();
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectedKey = iterator.next();
                    iterator.remove();
                    if (selectedKey.isAcceptable()) {
                        ServerSocketChannel channel = (ServerSocketChannel) selectedKey.channel();
                        SocketChannel sc = channel.accept();
                        sc.configureBlocking(false);
                        sc.register(selector, SelectionKey.OP_READ);
                    } else if (selectedKey.isReadable()) {
                        SocketChannel client = (SocketChannel) selectedKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int length = client.read(byteBuffer);
                        if (length == -1) {
                            client.close();
                        } else {
                            byteBuffer.flip();
                            byte[] buffer = new byte[byteBuffer.remaining()];
                            byteBuffer.get(buffer);
                            System.out.println(new String(buffer));
                        }
                    }
                }
            }
        }
    }
}
